import layui from 'layui';
import $$layui from 'top.layui';
import { version } from '../../package.json';

const MODULE_NAME = 'admin';

const ClassNames = {
  APP_SHRINK  : 'layadmin-layout-shrink',
  APP_MOBILE  : 'layadmin-layout-mobile',
  ICON        : 'layui-icon',
  ICON_SHRINK : 'layui-icon-shrink-right',
  ICON_SPREAD : 'layui-icon-spread-left',
  ICON_FULL   : 'layui-icon-screen-full',
  ICON_RESTORE: 'layui-icon-screen-restore',
  SHOW        : 'layui-show',
  THIS        : 'layui-this',
  CONTEXT_MENU: 'layadmin-pagetabs-contextmenu',
  BACKDROP    : 'layadmin-pagetabs-backdrop'
};

layui.define(['jquery', 'element', 'layer', 'setter', 'view'], function(exports) {
  const $ = layui.jquery;
  const element = layui.element;
  const layer = layui.layer;
  const setter = layui.setter;
  const view = layui.view;
  const device = layui.device();
  const hint = layui.hint();

  const GLOBAL_FILTER_PAGETABS = 'layadmin-pagetabs';

  const Selector = {
    APP        : setter.el,
    FLEX       : '#layadmin-flex',
    SIDEMENU   : '#layadmin-navmenu',
    GLOBALTABS : '#' + GLOBAL_FILTER_PAGETABS,
    CONTEXTMENU: '#' + ClassNames.CONTEXT_MENU,
    BACKDROP   : '#' + ClassNames.BACKDROP
  };

  const $window = $(window);
  const $body = $('body');

  const $app = $(Selector.APP);
  const $flex = $(Selector.FLEX);

  // eslint-disable-next-line eqeqeq
  const isTop = self == top;

  class Admin {
    constructor() {
      this.name = MODULE_NAME;
      this.version = version;
      this.isTop = isTop;
    }

    // 事件监听
    $on(eventType, callback) {
      return $$layui.onevent.call(this, MODULE_NAME, eventType, callback);
    }
    // 事件响应
    $emit(eventType, params) {
      return $$layui.event.call(this, MODULE_NAME, eventType, params);
    }
    // 时间移除
    $off(eventType) {
      return $$layui.off.call(this, eventType, MODULE_NAME);
    }

    // 屏幕类型
    screen(isCurrent) {
      const width = isCurrent ? $window.width() : $$layui.$(top.window).width();

      if (width >= 1600) {
        return 4; // xl
      } else if (width >= 1200) {
        return 3; // lg
      } else if (width >= 992) {
        return 2; // md
      } else if (width >= 768) {
        return 1; // sm
      } else {
        return 0; // xs
      }
    }

    // 项目基础弹窗
    popup(options) {
      return $$layui.view.popup(options);
    }

    // 项目右侧弹窗
    popupRight(options) {
      return $$layui.view.popupRight(options);
    }

    // 项目错误弹窗
    error(message) {
      return $$layui.view.error(message);
    }

    // 项目提示弹窗
    alert(options, type) {
      return $$layui.view.alert(options, type);
    }

    // 项目询问弹窗
    confirm(options) {
      return $$layui.view.confirm(options);
    }

    // 项目通知弹窗
    broadcast(options) {
      return $$layui.view.broadcast(options);
    }

    // 项目展示信息弹窗
    msg(...args) {
      return $$layui.layer.msg.apply($$layui.layer, args);
    }
  }

  var admin = $.extend({}, new Admin(), {
    // 侧边伸缩
    sideFlexible: function(status) {
      var screen = this.screen();
      // 手机模式
      if (screen < 2) {
        $app.addClass(ClassNames.APP_MOBILE);
      } else {
        $app.removeClass(ClassNames.APP_MOBILE);
      }

      // 切换伸缩按钮和侧边菜单的状态
      if (status === 'spread') { // 如果展开状态则收起
        $app.removeClass(ClassNames.APP_SHRINK);
        $flex.removeClass(ClassNames.ICON_SPREAD).addClass(ClassNames.ICON_SHRINK);
      } else {
        $app.addClass(ClassNames.APP_SHRINK);
        $flex.removeClass(ClassNames.ICON_SHRINK).addClass(ClassNames.ICON_SPREAD);
      }

      this.$emit('side-flexible', status);
    },

    // 记录最后一个标签
    tabsPage: {},

    // 获取当前页面
    tabsBody: function(index) {
      return $(Selector.GLOBALTABS).find('.layui-tab-content > .layui-tab-item').eq(index || 0);
    },

    tabsBodyChange: function(index, options) {
      options = options || {};
      this.tabsBody(index).addClass(ClassNames.SHOW).siblings().removeClass(ClassNames.SHOW);
      // 滚动条
      this.$emit('pagetabs', {
        index: index,
        id   : options.id,
        url  : options.url,
        text : options.text,
        tip  : options.tip
      });
    },

    // 获取完整的路径地址
    getAbsolutePath: function(path) {
      return path.indexOf(setter.base) === -1 ? (setter.base + (path.charAt(0) === '/' ? '' : '/') + path) : path;
    },

    // 全屏
    fullScreen: function() {
      var ele = document.documentElement;
      var reqFullScreen = ele.requestFullScreen || ele.webkitRequestFullScreen ||
      ele.mozRequestFullScreen || ele.msRequestFullscreen;
      if (typeof reqFullScreen !== 'undefined' && reqFullScreen) {
        reqFullScreen.call(ele);
      }
    },

    // 退出全屏
    exitScreen: function() {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    }
  });

  // 页面全局事件
  var events = admin.events = {
    // 伸缩
    flexible: function() {
      var isSpread = $flex.hasClass(ClassNames.ICON_SPREAD);
      admin.sideFlexible(isSpread ? 'spread' : '');
    },

    // 全屏
    fullscreen: function() {
      var $this = $(this);
      var $icon = $this.find('.' + ClassNames.ICON);

      if ($icon.hasClass(ClassNames.ICON_FULL)) {
        admin.fullScreen();
        $icon.addClass(ClassNames.ICON_RESTORE).removeClass(ClassNames.ICON_FULL);
      } else {
        admin.exitScreen();
        $icon.addClass(ClassNames.ICON_FULL).removeClass(ClassNames.ICON_RESTORE);
      }
    },

    // 登出
    logout: function() {
      admin.alert({
        title  : false,
        skin   : 'layadmin-view-popup-logout',
        content: '确定退出?',
        yes    : function(index) {
          admin.msg('退出成功');
        }
      }, 'warning');
    },

    // 刷新
    refresh: function() {
      if (admin.tabsPage.index >= length) {
        admin.tabsPage.index = length - 1;
      }
      var $frame = admin.pagetabsBody(admin.pagetabs.index).find('iframe');
      $frame[0].contentWindow.location.reload(true);

      events.closeContextMenu();
    },

    // 关闭当前
    closeThisTab: function() {
      element.tabDelete(GLOBAL_FILTER_PAGETABS, admin.tabsPage.id);
      events.closeContextMenu();
    },

    // 关闭其他
    closeOtherTabs: function(type) {
      var tabsPage = admin.tabsPage;
      var $tabs = $(Selector.GLOBALTABS).find('.layui-tab-title > li:gt(0)');

      $tabs.each(function() {
        var layId = $(this).attr('lay-id');
        (type === 'all' || layId !== tabsPage.id) && element.tabDelete(GLOBAL_FILTER_PAGETABS, layId);
      });

      events.closeContextMenu();
    },

    closeAllTabs: function() {
      events.closeOtherTabs('all');
    },

    // 关闭右键菜单
    closeContextMenu: function() {
      $body.find(Selector.CONTEXTMENU).remove();
      $(Selector.BACKDROP).hide();
    },

    openWindow: function() {

    },

    shade: function() {
      admin.sideFlexible();
    },

    setter: function() {
      admin.popupRight({
        id     : 'layadmin-popup-setter',
        success: function(layero, index) {
          view('#' + this.id).render('setter', { themes: ['#009688', '#2F4056', '#1E9FFF'] });
        }
      });
    }
  };

  // 初始
  !(function() {
    // 不开启页面标签时
    if (!setter.pageTabs) {
      // $('#LAY_app_tabs').addClass(HIDE);
      // container.addClass('layadmin-tabspage-none');
    }

    // 低版本IE提示
    if (device.ie && device.ie < 10) {
      view.error('IE' + device.ie + '下访问可能不佳，推荐使用：Chrome / Firefox / Edge 等高级浏览器');
    }
  }());

  element.on('tab(' + GLOBAL_FILTER_PAGETABS + ')', function(data) {
    admin.tabsPage.index = data.index;
    var $thisTitle = data.elem.children('.layui-tab-title').find('.' + ClassNames.THIS);
    var $thisContent = data.elem.children('.layui-tab-content>.layui-tab-item:eq(' + data.index + ')');
    admin.tabsBodyChange(data.index, {
      id   : $thisTitle.attr('lay-id'),
      url  : $thisContent.find('iframe').attr('src'),
      title: $thisTitle.children('span').text(),
      tips : $thisTitle.children('span').attr('title')
    });
  });

  $body.on('contextmenu', Selector.GLOBALTABS + '>.layui-tab-title>li', function(e) {
    e.preventDefault();

    var $this = $(this);
    var layLock = $this.attr('lay-lock');

    var windowWidth = $window.width();
    var mousePoint = e.clientX;

    $body.find(Selector.CONTEXTMENU).remove();

    var $menu = $([
      '<ul class="' + ClassNames.CONTEXT_MENU + '" id="' + ClassNames.CONTEXT_MENU + '">',
      layLock === 'true' ? '' : '<li layadmin-event="closeThisTab"><a href="javascript:;">关闭当前</a></li>',
      '<li layadmin-event="closeOtherTabs"><a href="javascript:;">关闭其他</a></li>',
      layLock === 'true' ? '' : '<li layadmin-event="closeAllTabs"><a href="javascript:;">关闭全部</a></li>',
      '</ul>'
    ].join(''));

    var $backdrop = $(Selector.BACKDROP);

    if ($backdrop.length <= 0) {
      $backdrop = $('<div id="' + ClassNames.BACKDROP + '" layadmin-event="closeContextMenu" />');
      $backdrop.css({
        position: 'fixed',
        top     : 0,
        right   : 0,
        bottom  : 0,
        left    : 0,
        zIndex  : 20000,
        opacity : 0,
        display : 'none'
      });
      $body.append($backdrop);
    }

    $menu.on('contextmenu', function(e) {
      e.preventDefault();
    });

    $menu.css({
      top : e.clientY + 'px',
      left: ((windowWidth - mousePoint < 105) ? (windowWidth - 105) : mousePoint) + 'px'
    });
    $body.append($menu);
    $backdrop.show();
  });

  $body.on('click', '*[layadmin-event]', function() {
    var $this = $(this);
    var action = $this.attr('layadmin-event');
    // if ($this.parent().hasClass('layui-nav-child')) {
    //   $this.parent().removeClass(ClassName.SHOW);
    // }
    $.isFunction(events[action]) && events[action].call(this);
  });

  // 所有的页面跳转
  $body.on('click', '*[layadmin-href]', function() {
    var $this = $(this);
    var id = $this.data('id');
    var href = $this.attr('layadmin-href');
    var text = $this.data('label') || $this.attr('lay-text') || $this.attr('title') || $this.text();
    var tips = $this.data('tips');

    admin.tabsPage.elem = $this;
    var topLayui = parent === self ? layui : top.layui;
    topLayui.index.openPage({
      id  : id,
      url : href,
      text: text,
      tip : tips
    });
  });

  // 窗口resize事件
  var resizeSystem = layui.data.resizeSystem = function() {
  // layer.close(events.note.index);
    layer.closeAll('tips');

    if (!resizeSystem.lock) {
      setTimeout(function() {
        admin.sideFlexible(admin.screen() < 2 ? '' : 'spread');
        delete resizeSystem.lock;
      }, 100);
    }

    resizeSystem.lock = true;
  };
  $window.on('resize', layui.data.resizeSystem);

  exports(MODULE_NAME, admin);
});
